import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import Web3 from 'web3';
import './PurchaseProduct.css'; // 引入CSS文件

const PurchaseProduct = ({ productId, web3, marketplaceContract }) => {
    const { userAddr } = useParams();
    const [quantity, setQuantity] = useState('');

    const purchaseProduct = async () => {
        try {
            const accounts = await web3.eth.requestAccounts();
            const product = await marketplaceContract.methods.products(productId).call();
            console.log("product.seller, userAddr, productId, quantity", product.seller, userAddr, productId, quantity)
            await marketplaceContract.methods.purchaseProduct(product.seller, userAddr, productId, quantity).send({ from: accounts[0] });
            alert('商品购买成功');
        } catch (error) {
            console.error('商品购买失败', error);
        }
    };

    return (
        <div className="purchase-container">
            <input
                type="number"
                placeholder="购买数量"
                value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
                className="purchase-input"
            />
            <button onClick={purchaseProduct} className="purchase-button">购买</button>
        </div>
    );
};

export default PurchaseProduct;
